function euler % euler method for various M values when solving % y' = ry(1-y) with y(0) = y0 ' % clear all previous variables and plots clear * clf % parameters for calculation r=10; t0=0; y0=0.01; tmax=1; % get(gcf) % set(gcf,'Position', [1203 732 515 307]); plotsize(515, 307) % calculate and plot exact solution tt=linspace(t0,tmax,100); a0=(1-y0)/y0; for it=1:100 exact(it)=1/(1+a0*exp(-r*tt(it))); end; plot(tt,exact,'k','LineWidth',1) hold on % define axes and title used in plot xlabel('t-axis','FontSize',14,'FontWeight','bold') ylabel('Solution','FontSize',14,'FontWeight','bold') say=['Solving Logistic Equation Using Euler Method']; title(say,'FontSize',14,'FontWeight','bold') % have MATLAB use certain plot options (all are optional) box on axis([0 1 0 1.05]) set(gca,'ytick',[0 0.2 0.4 0.6 0.8 1.0]); set(gca,'FontSize',14); % loop used to increase M value M=1; for icounter=1:4 M=M*4 % calculate Euler solution t=linspace(t0,tmax,M+1); h=t(2)-t(1); euler=y0; y=y0; for i=2:M+1 yy=y+r*h*y*(1-y); euler=[euler, yy]; y=yy; end; % plot solution if icounter==1 plot(t,euler,'--ro','MarkerSize',7) legend(' Exact',' Euler (M = 4)',2) set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold') pause elseif icounter==2 plot(t,euler,'--b*','MarkerSize',7) legend(' Exact',' Euler (M = 4)',' Euler (M = 16)',2) set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold') pause elseif icounter==3 plot(t,euler,'--mo','MarkerSize',7) legend(' Exact',' Euler (M = 4)',' Euler (M = 16)',' Euler (M = 64)',2) set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold') pause elseif icounter==4 plot(t,euler,'-r','LineWidth',1) legend(' Exact',' Euler (M = 4)',' Euler (M = 16)',' Euler (M = 64)',' Euler (M = 256)',2) set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold') end; end hold off % subfunction plotsize function plotsize(width,height) siz=get(0,'ScreenSize'); bottom=max(siz(4)-height-95,1); set(gcf,'Position', [2 bottom width height]);